package com.huanying.sales.region;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huanying.framework.BaseDao;
import com.huanying.sales.building.Building;
import com.huanying.sales.project.ProjectController;

@Service
public class RegionServiceImpl implements RegionService {
	Logger logger = Logger.getLogger(RegionServiceImpl.class);
	
	@Autowired
	private BaseDao dao;

	@Override
	public void add(Region region) throws Exception {
		Session session = dao.getNewSession();
		Transaction tx = session.beginTransaction();
		try {
			session.save(region);
			int l= region.getTotal_num();
			for(int i=0;i<l;i++){
				Building  b = new Building();
				b.setBuilding_num(new Integer(i+1).toString());
				b.setRegion_id(region.getId());
				b.setStatus(1);
				session.save(b);
			}
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			logger.error("新建分区失败", e);
			throw e;
		}
		finally {
			session.flush();
			session.clear();
			session.close();
		}
	}
		

	@Override
	public void update(Region region) throws Exception {
		dao.update(region);
	}

	@Override
	public Region get(int id) throws Exception {
		Region region = (Region)dao.load(Region.class, id);
		return region;
	}

	@Override
	public List getByPorjectId(int project_id) throws Exception {
		String hql = "from Region where status=1 and project_id=:project_id";
		Region r = new Region();
		r.setProject_id(project_id);
		List regions = dao.exculeHql(hql, r);
		return regions;
	}

	@Override
	public int delete(Region region) throws Exception {
		int flag = 0;
		Session session = dao.getNewSession();
		Transaction tx = session.beginTransaction();
		String hql_r = "update Region set status=0 where id=?";
		String hql_b = "delete Building where region_id=?";
		try {
			Query query = session.createQuery(hql_r);
			query.setInteger(0, region.getId());
			query.executeUpdate();
			query = session.createQuery(hql_b);
			query.setInteger(0, region.getId());
			query.executeUpdate();
			tx.commit();
			flag = 1;
		} catch (Exception e) {
			tx.rollback();
			logger.error("删除分区失败", e);
			flag = 0;
			throw e;
		} finally {
			session.flush();
			session.clear();
			session.close();
		}
		return flag;
	}

}
